'use strict';
const dayjs = require("dayjs");

module.exports = app => {
    const { STRING, INTEGER, DATE, BOOLEAN } = app.Sequelize;
    const Address = app.model.define(
        'Address',
        {
            id: { type: INTEGER, primaryKey: true, autoIncrement: true },
            member_user_id: { type: INTEGER, allowNull: false, comment: '用户ID' },
            name: { type: STRING(100), allowNull: false, comment: '收货人姓名' },
            phone: { type: STRING(20), allowNull: false, comment: '联系电话' },
            province: { type: STRING(50), allowNull: false, comment: '省份' },
            city: { type: STRING(50), allowNull: false, comment: '城市' },
            district: { type: STRING(50), allowNull: false, comment: '区/县' },
            address: { type: STRING(255), allowNull: false, comment: '详细地址' },
            is_default: { type: BOOLEAN, defaultValue: false, comment: '是否为默认地址' },
            create_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            updated_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('updated_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            }
        },
        {
            tableName: 'address',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'updated_time'
        }
    );
    
    Address.associate = function() {
        app.model.Address.belongsTo(app.model.MemberUser, { foreignKey: 'member_user_id', targetKey: 'id', as: 'user' });
    };
    
    return Address;
};

// 创建mysql建表语句
// CREATE TABLE `address` (
//   `id` int(11) NOT NULL AUTO_INCREMENT,
//   `member_user_id` int(11) NOT NULL COMMENT '用户ID',
//   `name` varchar(100) NOT NULL COMMENT '收货人姓名',
//   `phone` varchar(20) NOT NULL COMMENT '联系电话',
//   `province` varchar(50) NOT NULL COMMENT '省份',
//   `city` varchar(50) NOT NULL COMMENT '城市',
//   `district` varchar(50) NOT NULL COMMENT '区/县',
//   `address` varchar(255) NOT NULL COMMENT '详细地址',
//   `is_default` tinyint(1) DEFAULT '0' COMMENT '是否为默认地址',
//   `create_time` datetime DEFAULT NULL,
//   `updated_time` datetime DEFAULT NULL,
//   PRIMARY KEY (`id`),
//   KEY `idx_member_user_id` (`member_user_id`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='收货地址表';
